package com.leyou.search.service.impl;

import com.leyou.common.exception.LyException;
import com.leyou.item.clients.ItemClient;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.entity.Goods;
import com.leyou.search.respository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.entity.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.xml.builders.BooleanQueryBuilder;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ItemClient itemClient;

    @Override
    public Mono<List<String>> getSuggest(String key) {
        return goodsRepository.suggestBySingleField("suggestion", key);
    }

    @Override
    public Mono<PageInfo<Goods>> listData(SearchRequest searchRequest) {
        QueryBuilder queryBuilder = getQueryBuilder(searchRequest);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.query(queryBuilder);
        return null;
    }

    private QueryBuilder getQueryBuilder(SearchRequest searchRequest) {
        String key = searchRequest.getKey();
        if (StringUtils.isEmpty(key)) {
            throw new LyException(400, "请求参数有误!");
        }

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        boolQueryBuilder.must(QueryBuilders.matchQuery("title", key).operator(Operator.AND));

        Map<String, String> filters = searchRequest.getFilters();

        if (!CollectionUtils.isEmpty(filters)) {
            filters.entrySet().forEach(entry -> {
                String eKey = entry.getKey();
                String eValue = entry.getValue();

                if ("分类".equals(eKey)) {
                    eKey = "categoryId";
                    boolQueryBuilder.filter(QueryBuilders.termQuery(eKey, eValue));
                } else if ("品牌".equals(eKey)) {
                    eKey = "brandId";
                    boolQueryBuilder.filter(QueryBuilders.termQuery(eKey, eValue));
                }
            });
        }

        return boolQueryBuilder;
    }

    @Override
    public Mono<Map<String, List<?>>> listFilter(SearchRequest searchRequest) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.query(getQueryBuilder(searchRequest));

        sourceBuilder.aggregation(AggregationBuilders.terms("brandAgg").field("brandId").size(20));
        sourceBuilder.aggregation(AggregationBuilders.terms("categoryAgg").field("categoryId").size(20));

        sourceBuilder.aggregation(
                AggregationBuilders.nested("specAgg", "specs")
                        .subAggregation(AggregationBuilders.terms("nameAgg").field("specs.name")
                                .subAggregation(AggregationBuilders.terms("valueAgg").field("specs.value")))
        );

        Mono<Aggregations> aggregationsMono = this.goodsRepository.aggregationBySourceBuilder(sourceBuilder);

        return aggregationsMono.map(aggregations -> {
            Map<String, List<?>> resultMap = new LinkedHashMap<>();

            Terms brandAgg = aggregations.get("brandAgg");

            List<Long> brandIds = brandAgg
                    .getBuckets()
                    .stream()
                    .map(bucket -> ((Terms.Bucket) bucket).getKeyAsNumber())
                    .map(Number::longValue)
                    .collect(Collectors.toList());

            Terms categoryAgg = aggregations.get("categoryAgg");

            List<Long> categoryIds = categoryAgg
                    .getBuckets()
                    .stream()
                    .map(bucket -> ((Terms.Bucket) bucket).getKeyAsNumber())
                    .map(Number::longValue)
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(categoryIds)) {
                resultMap.put("分类", this.itemClient.queryCategoryByIds(categoryIds));
            }
            if (!CollectionUtils.isEmpty(brandIds)) {
                resultMap.put("品牌", this.itemClient.queryBrandByIds(brandIds));
            }

            Nested specAgg = aggregations.get("specAgg");
            Terms nameAgg = specAgg.getAggregations().get("nameAgg");
            nameAgg.getBuckets().forEach(bucket -> {
                String key = ((Terms.Bucket) bucket).getKeyAsString();
                Terms valueAgg = ((Terms.Bucket) bucket).getAggregations().get("valueAgg");
                List<String> valueList = valueAgg.getBuckets()
                        .stream()
                        .map(valueBucket -> ((Terms.Bucket) valueBucket).getKeyAsString())
                        .collect(Collectors.toList());
                resultMap.put(key, valueList);
            });

            return resultMap;
        });
    }
}